package com.github.boluo1230.wechat.service.mp.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.boluo1230.wechat.entity.MpApp;
import com.github.boluo1230.wechat.entity.detail.ReplyDetails;
import com.github.boluo1230.wechat.entity.message.WxCustomMsg;
import com.github.boluo1230.wechat.entity.message.WxCustomText;
import com.github.boluo1230.wechat.entity.vo.WxResponse;
import com.github.boluo1230.wechat.feign.WxMessageAPI;
import com.github.boluo1230.wechat.service.mp.SendMessageServive;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author Code Farmer
 * @date 2019/10/16 14:33
 */
@Service
public class SendMessageServiceImpl implements SendMessageServive {

    @Autowired
    private WxMessageAPI wxMessageAPI;

    @Override
    public void sendReplyList(MpApp mpApp, String openId, List<ReplyDetails> replyDetailsList) {
        if (replyDetailsList == null || replyDetailsList.size() == 0) {
            return;
        }
        for (int i = 0; i < replyDetailsList.size(); i++) {
            ReplyDetails replyDetails = replyDetailsList.get(i);
            String msgType = replyDetails.getType();
            Map<String, Object> params = new ConcurrentHashMap<>();
            params.put("touser", openId);
            params.put("msgtype", msgType);

            if (msgType.equals("text")) {
                Map<String, String> textParam = replyDetails.getContent();
                params.putAll(textParam);
            } else if (msgType.equals("news")) {
                Map<String, String> newsParam = replyDetails.getContent();
                params.put("articles", newsParam);
            } else {
                Map<String, String> mediaParam = replyDetails.getContent();
                params.putAll(mediaParam);
            }
            this.sendOneMessage(mpApp, openId, params, replyDetails.getDelay());
        }
    }

    //todo
    private void sendOneMessage(MpApp mpApp, String openId, Map<String, Object> params, int delay) {

        WxCustomMsg wxCustomMsg = new WxCustomText(openId, (String) params.get("content"));
        String accessToken = "26_WFDXflJLozjgc1Uwh2YS4Af2CNd3vJ2fa68JAo7_dLAkxYIG1C1d4uHudqHWTJDLtNa-07_dT2E_IJCU-iSpNk00QZWyFzCEhHo8Vc2l3TIIs4g17y7-n7DQ4cJC51Kny_bxz1QgrHObOydVPZEcAIAWGL";
        WxResponse wxResponse = wxMessageAPI.sendCustomMessage(accessToken, wxCustomMsg);
        System.out.println(JSONObject.toJSONString(wxResponse));

    }
}
